import { memo } from 'react'
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom'
import { Layout, theme, FloatButton, Tooltip, message } from 'antd';
import { LogoutOutlined, FolderOutlined, EditOutlined, TableOutlined, FileOutlined, RollbackOutlined, UpOutlined, HomeOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { showMessage } from '@/store/modules/message';
import { clearUserInfo } from '@/store/modules/user';
import { clearToken } from '@/utils';
import { useParams } from 'react-router-dom';
import { MemoDocDetailSide } from './component/DocDetailSide';
import { MemoDocDetailHead } from './component/DocDetailHead'
import { getDocDetailsByDocId, saveDocMessage } from './api';
import SimpleEditor from '@/components/Tiptap/tiptap-templates/simple/simple-editor'
import styles from './index.module.less';
const { Content } = Layout;

const DocDetail = () => {
    // 退出登录功能
    const exit = () => {
        dispatch(showMessage({ message: '退出成功', type: 'success' }))
        dispatch(clearUserInfo())
        clearToken()
        navigate('/login')
    }

    // 返回功能
    const back = async () => {
        const saved = await handleSave(false); // 调用保存，但不显示"保存成功"消息
        if (saved) {
            dispatch(showMessage({ message: '已为您保存', type: 'success' }));
            setTimeout(() => {
                navigate('/docList');
            }, 1000);
        }
        // 如果保存失败，handleSave内部会显示错误信息，且不会跳转
    }

    // 返回首页功能
    const goHome = () => {
        navigate('/')
    }

    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const dispatch = useDispatch();
    const navigate = useNavigate()
    const { id } = useParams();
    const [docName, setDocName] = useState('');
    const [docContent, setDocContent] = useState(null);
    const location = useLocation();
    const { id: docId } = useParams();
    const editorRef = useRef();

    // 权限状态
    const [docPermission, setDocPermission] = useState('');
    // 是否通过分享码加入协作
    const [isJoinedViaShareCode, setIsJoinedViaShareCode] = useState(false);

    // 保存文档的方法
    const handleSave = async (showSuccessMessage = true) => {
        if (!docName || !docContent) {
            message.error('文档名称和内容不能为空');
            return false;
        }
        const userId = localStorage.getItem('userId');
        const data = {
            docId: id === 'new' ? undefined : id, // 新建时不传docId
            docName,
            userId,
            docPermission,
            docContent: JSON.stringify(docContent),
            isBelongToKnowledgeBase: '0',
            knowledgeBaseId: ''
        };
        try {
            const res = await saveDocMessage(data);
            if (res && res.code === 200) {
                if (showSuccessMessage) {
                    message.success('保存成功');
                }
                // 如果是新建文档，则在保存后跳转到新文档的详情页
                if (id === 'new' && res.data) {
                    navigate(`/docList/docDetail/${res.data}`);
                }
                return true;
            } else {
                message.error(res?.msg || '保存失败');
                return false;
            }
        } catch (err) {
            message.error('保存失败');
            return false;
        }
    };

    const [content, setContent] = useState('')
    const transformToMenuItems = (data) => {
        return data.map(item => {
            const returnKey = () => {
                if (item.folderId === null) {
                    if (item.status === 1) {
                        return `/content/main/${item.id}`
                    }
                    if (item.status === 2) {
                        return `/home/list/${item.id}`
                    }
                    if (item.status === 3) {
                        return `/excel/main/${item.id}`
                    }
                    if (item.status === 4) {
                        return `file${item.id}`
                    }
                } else {
                    if (item.status === 1) {
                        return `/content/${item.folderId}/${item.id}`
                    }
                    if (item.status === 2) {
                        return `/home/list/${item.id}`
                    }
                    if (item.status === 3) {
                        return `/excel/${item.folderId}/${item.id}`
                    }
                    if (item.status === 4) {
                        return `file${item.id}`
                    }
                }
            }
            const returnIcon = () => {
                if (item.status === 1) return <EditOutlined />
                if (item.status === 2) return <FolderOutlined />
                if (item.status === 3) return <TableOutlined />
                if (item.status === 4) return <FileOutlined />
            }
            return {
                key: returnKey(),
                icon: returnIcon(),
                label: (
                    <Tooltip title={item.name}>
                        {item.name}
                    </Tooltip>
                )
                ,
                children: item.children && item.children.length > 0
                    ? transformToMenuItems(item.children)
                    : undefined,
            }
        });
    };

    useEffect(() => {
        if (location.state && location.state.docName) {
            setDocName(location.state.docName || '');
            setDocContent(
                location.state.docContent
                    ? (typeof location.state.docContent === 'string'
                        ? JSON.parse(location.state.docContent)
                        : location.state.docContent)
                    : { type: 'doc', content: [] }
            );
            setDocPermission(location.state.docPermission || '仅阅读');
            // 标记为通过分享码加入
            setIsJoinedViaShareCode(location.state.isJoinedViaShareCode || false);
        } else if (id === 'new') {
            setDocName('未命名文档');
            setDocContent({ type: 'doc', content: [] });
            setDocPermission('可编辑');
        } else if (id) {
            getDocDetailsByDocId(id).then(res => {
                if (res && res.code === 200 && res.data) {
                    setDocName(res.data.docName || '未命名文档');
                    let content = '';
                    try {
                        content = res.data.docContent
                            ? (typeof res.data.docContent === 'string'
                                ? JSON.parse(res.data.docContent)
                                : res.data.docContent)
                            : { type: 'doc', content: [] };
                    } catch (e) {
                        content = { type: 'doc', content: [] };
                    }
                    setDocContent(content);
                    setDocPermission(res.data.docPermission || '仅阅读');
                }
            });
        }
    }, [id, location.state]);


    return (
        <Layout className={styles.docDetailLayout}>
            <FloatButton.Group
                shape="circle"
                trigger="hover"
                type="primary"
                icon={<UpOutlined />}
                style={{
                    insetInlineEnd: 38,
                    insetBlockEnd: 100 
                }}
            >
                <FloatButton
                    icon={<LogoutOutlined />}
                    onClick={exit}
                    tooltip="退出登录"
                />
                <FloatButton
                    icon={<RollbackOutlined />}
                    onClick={back}
                    tooltip="返回文档列表"
                />
                <FloatButton
                    icon={<HomeOutlined />}
                    onClick={goHome}
                    tooltip="返回首页"
                />
            </FloatButton.Group>
            {/* <MemoDocDetailSide /> */}
            <Layout>
                {/* 右侧 */}
                <Content className={styles.docDetailContent}>
                    {/* 顶部 */}
                    <MemoDocDetailHead
                        docId={id}
                        docName={docName}
                        setDocName={setDocName}
                        docPermission={docPermission}
                        setDocPermission={setDocPermission}
                        docContent={docContent}
                        setDocContent={setDocContent}
                        isJoinedViaShareCode={isJoinedViaShareCode}
                        onSave={handleSave}
                    />
                    {/* 编辑器写在这 */}
                    <Content
                        className={styles.docDetailHeadContent}
                        style={{
                            background: theme.useToken().token.colorBgContainer,
                        }}
                    >
                        <div className={styles.docDetailEditorWrap}>
                            <SimpleEditor
                                ref={editorRef}
                                content={docContent}
                                onContentChange={setDocContent}
                                docId={docId}
                                className={styles.docDetailEditor}
                            />
                            {docPermission === '仅阅读' && (
                                <div
                                    className={styles.docDetailReadMask}
                                    onClick={e => e.preventDefault()}
                                    onMouseDown={e => e.preventDefault()}
                                />
                            )}
                        </div>
                    </Content>
                </Content>
            </Layout>
        </Layout>
    );
}

export const MemoDocDetail = memo(DocDetail)